<?php

abstract class BaseController {

    protected $view;
    protected $messages;
    protected $js_path;
    protected $css_path;

    public function __construct() {
        $this->view = new BaseView(new Request);
        $this->messages = new Messages();
        $this->js_path = VIEW_PATH . DS . $this->name_for_url() . DS . 'js' . DS;
    }

    abstract public function index();

    function name_for_url() {
        return strtolower(substr(get_class($this), 0, strlen(get_class($this)) - strlen(SUFFIX_CLASS_CONTROLLER)));
    }

    function array_json($collection, $settings) {
        $result = array();
        foreach ($collection as $item):
            array_push($result, $item->to_json($settings));
        endforeach;
        $result = implode(',', $result);
        return "[$result]";
    }
    
    function add_css_tags($ref, $html_attributes = array()){
        $this->view->add_css_tags($ref, $html_attributes);
    }
    
    protected function getLibrary($libreria) {
        $rutaLibreria = ROOT . 'libs' . DS . $libreria . '.php';

        if (is_readable($rutaLibreria)) {
            require_once $rutaLibreria;
        } else {
            throw new Exception('Error de libreria');
        }
    }

    protected function redirect_to($controller, $method = '', $args = array()) {
        header('location:' . $this->get_url($controller, $method, $args));
    }

    protected function render($view = false) {
        if(is_callable(array($this, 'before_render'))):
            $this->before_render();
        endif;
        $this->set('messages', $this->messages);
        //$this->autoload();
        if ($view):
            $this->view->display($view);
        else:
            $this->view->display($this->view_name());
        endif;
    }

    protected function view_name() {
        $a = debug_backtrace();
        return($a[2]["function"]);
    }

    protected function set($attr_name, $attr_value) {
        $this->view->set_value($attr_name, $attr_value);
    }

    protected function set_message($name, $message) {
        $this->messages->set($name, $message);
    }

    protected function get_method_url($method, $args = array()) {
        return $this->get_url($this->name_for_url(), $method, $args);
    }

    protected function get_url($controller, $method, $args = array()) {
        $url_components = array_merge(array($controller, $method), $args);
        return BASE_URL . implode("/", $url_components);
    }
}

?>
